package com.zbp.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.zbp.mapper.UserMapper;
import com.zbp.model.User;
import com.zbp.model.UserRole;
import com.zbp.model.vo.UserVO;
import com.zbp.service.IRoleService;
import com.zbp.service.IUserRoleService;
import com.zbp.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

import static com.zbp.model.table.UserRoleTableDef.USER_ROLE;
import static com.zbp.model.table.UserTableDef.USER;


@Service
public class IUserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private UserMapper UserMapper;

    @Autowired
    private IUserRoleService userRoleService;

    @Autowired
    private IRoleService roleService;

    @Override
    public User get(Long id) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.where(USER.ID.eq(id))
                .and(USER.STATUS.eq(0));
        return UserMapper.selectOneByQuery(queryWrapper);
    }

    @Override
    public UserVO get(String userName) {
        QueryWrapper userQuery = new QueryWrapper();
        userQuery.where(USER.NAME.eq(userName))
                .and(USER.STATUS.eq(0));
        UserVO userVO = this.getOneAs(userQuery, UserVO.class);
        if (ObjectUtil.isNotNull(userVO)) {
            QueryWrapper userRoleQuery = new QueryWrapper();
            userRoleQuery.where(USER_ROLE.USER_ID.eq(userVO.getId()));
            List<UserRole> userRoleList = userRoleService.list(userRoleQuery);
            if (!userRoleList.isEmpty()) {
                List<String> roleIds = userRoleList.stream().map(UserRole::getRoleId).collect(Collectors.toList());
                userVO.setRoleList(roleService.listByIds(roleIds));
            }
        }
        return userVO;
    }

    @Override
    public User create(User User) {
        UserMapper.insert(User);
        return this.get(User.getId());
    }

    @Override
    public User update(User User) {
        UserMapper.update(User);
        return this.get(User.getId());
    }

    @Override
    public Integer delete(Long id) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.where(USER.ID.eq(id));
        return UserMapper.deleteByQuery(queryWrapper);
    }
}
